package com.blb.productservice.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.productservice.pojo.Product;
import com.blb.productservice.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/product/{id}")
    @SentinelResource(value = "product/{id}",
//            blockHandlerClass = ProductBlockHandler.class,
//            blockHandler = "getProductByIdBlockHandler",
            fallbackClass = ProductFallback.class,
            fallback = "getProductByIdFallback")
    public ResponseEntity<Product> getProductById(@PathVariable Long id){
//        if(new Random().nextBoolean()){
//            throw new RuntimeException("Error");
//        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Product product = productService.getById(id);
        return ResponseEntity.ok(product);
    }

    @GetMapping("/products-page")
    public ResponseEntity<Page<Product>> getProductPage(@RequestParam(required = false,defaultValue = "1")Long current,
                                                        @RequestParam(required = false,defaultValue = "5")Long size){
        Page<Product> page = productService.page(new Page<>(current, size));
        return ResponseEntity.ok(page);
    }

    @PostMapping("/product")
    public ResponseEntity<Product> addProduct(@RequestBody Product product){
        productService.save(product);
        return ResponseEntity.ok(product);
    }

    @PutMapping("/product")
    public ResponseEntity<Product> updateProduct(@RequestBody Product product){
        productService.updateById(product);
        return ResponseEntity.ok(product);
    }

    @DeleteMapping("/product/{id}")
    public ResponseEntity<Long> deleteProduct(@PathVariable Long id){
        productService.removeById(id);
        return ResponseEntity.ok(id);
    }

    @GetMapping("/hello")
    @SentinelResource(value = "hello",blockHandlerClass = ProductBlockHandler.class,
            blockHandler = "helloBlockHandler")
    public String hello(){
        System.out.println(Thread.currentThread().getName()+"--->" + System.currentTimeMillis());
        return "Hello!";
    }
}
